package ntd.util.frame.storage.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import ntd.util.ComConfig;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.storage.NtdStorage;
import ntd.util.util.ToolDuration;

import java.io.InputStream;

public class NtdStorageLocal implements NtdStorage {

    private static final String LOCAL_FILE_PATH = ComConfig.com.getStr("com.file.path");

    @Override
    public void store(String bucketName, byte[] bytes, String name) {
        String path = LOCAL_FILE_PATH + bucketName;
        if (!FileUtil.exist(path)) {
            FileUtil.mkdir(path);
        }
        // 保存文件
        String absPath = StrUtil.format("{}/{}", path, name);
        ToolDuration.duration(() -> {
            FileUtil.writeBytes(bytes, absPath);
        }, "本地文件存储 - " + absPath);
    }

    @Override
    public InputStream loadInputStream(String bucketName, String name) {
        String path = LOCAL_FILE_PATH + bucketName;
        if (!FileUtil.exist(path)) {
            throw new ComException("找不到该bucket - {}", bucketName);
        }
        String absPath = StrUtil.format("{}/{}", path, name);
        if (!FileUtil.exist(absPath)) {
            throw new ComException("找不到该文件 - {}", name);
        }
        return FileUtil.getInputStream(absPath);
    }

    @Override
    public void delete(String bucketName, String name) {
        String path = LOCAL_FILE_PATH + bucketName;
        if (!FileUtil.exist(path)) {
            throw new ComException("找不到该bucket - {}", bucketName);
        }
        String absPath = StrUtil.format("{}/{}", path, name);
        if (!FileUtil.exist(absPath)) {
            throw new ComException("找不到该文件 - {}", name);
        }
        FileUtil.del(absPath);
    }

    @Override
    public String generateUrl(String bucketName, String name) {
        return null;
    }
}
